package org.itboys.framework.rpc;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.itboys.redis.RedisCacheClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 分布式session
 */
public class RemoteServletHolder implements RpcServletHolder{

    private static final String SESSION_KEY_PREFIX = "SS-";

    private int expireTime; //失效时间 单位 秒

    private RedisCacheClient redisCacheClient;

    @Override
    public <T> boolean addToSession(HttpServletRequest request, HttpServletResponse response, String sessionKey, T value) {
        String sessionId = getSessionId(request);
        String redisKey = SESSION_KEY_PREFIX+sessionId;
        Map<String, Object> sessionMap = redisCacheClient.get(redisKey, Map.class);
        if (sessionMap == null) {
            sessionMap = Maps.newHashMap();
        }
        sessionMap.put(sessionKey, value);
        response.setHeader(SESSION_KEY,sessionId);
        redisCacheClient.set(redisKey, value, expireTime);
        return true;
    }

    @Override
    public Object getValueFromSession(HttpServletRequest request, HttpServletResponse response, String sessionKey) {
        String sessionId = getSessionId(request);
        String redisKey = SESSION_KEY_PREFIX+sessionId;
        Map<String, Object> sessionMap = redisCacheClient.get(redisKey, Map.class);
        if (sessionMap == null) {
            return null;
        }
        return sessionMap.get(sessionKey);
    }

    public void setExpireTime(int expireTime) {
        this.expireTime = expireTime;
    }

    public void setRedisCacheClient(RedisCacheClient redisCacheClient) {
        this.redisCacheClient = redisCacheClient;
    }

}
